package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by admin on 2019/8/8.
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Reference
    private IUserInfoRedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {

            HandlerMethod handlerMethod = (HandlerMethod) handler;

            if (handlerMethod.hasMethodAnnotation(RequireLogin.class)) {

                String token = CookieUtil.getCookie(request);
                UserInfo userInfo = redisService.getUserInfoToken(token);
                if (userInfo == null) {
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        return true;
    }
}
